<template>
  <div class="user-page">
    <Header />

    <div class="user-container">
      <!-- 用户信息卡片 -->
      <div class="user-profile">
        <div class="profile-banner">
          <div class="avatar-wrapper">
            <img :src="userAvatar" alt="用户头像" class="avatar">
          </div>
          <div class="user-info">
            <h2 class="username">{{ username }}</h2>
            <p class="user-title">莫落</p>
          </div>
        </div>
      </div>

      <!-- 导航标签 -->
      <div class="nav-tabs">
        <div
            v-for="tab in tabs"
            :key="tab.id"
            :class="['tab-item', { active: currentTab === tab.id }]"
            @click="currentTab = tab.id"
        >
          {{ tab.name }}
        </div>
      </div>

      <!-- 订单列表 -->
      <div v-if="currentTab === 'orders'" class="orders-list" v-loading="loading">
        <div v-for="order in orders" :key="order.id" class="order-item">
          <div class="order-header">
            <span class="order-time">{{ formatDate(order.order_time) }}</span>
            <span class="order-number">订单号：{{ order.order_number }}</span>
          </div>

          <!-- 遍历订单中的课程 -->
          <div v-for="courseItem in order.order_details" :key="courseItem.course.id" class="order-content">
            <img :src="courseItem.course.course_img" alt="课程封面" class="course-cover">
            <div class="course-info">
              <h3 class="course-title">{{ courseItem.course.name }}</h3>
              <p class="course-desc">{{ courseItem.course.brief }}</p>
              <div class="validity">
                <span>有效期：{{ courseItem.expire_text }}</span>
                <span class="price">¥{{ courseItem.price }}</span>
              </div>
              <div class="teacher-info">
                <span>讲师：{{ courseItem.course.teacher.name }}</span>
                <span class="teacher-title">{{ courseItem.course.teacher.title }}</span>
              </div>
            </div>
            <div class="order-status">
              <span :class="['status-tag', order.order_status === 1 ? 'success' : 'pending']">
                {{ order.order_status_text }}
              </span>
              <div class="action-buttons">
                <button
                    v-if="order.order_status === 1"
                    class="study-btn"
                    @click="startStudy(order, courseItem.course)"
                >
                  立即学习
                </button>
              </div>
            </div>
          </div>

          <!-- 订单总价 -->
          <div class="order-footer">
            <div class="order-total">
              <span>订单总价：</span>
              <span class="total-price">¥{{ order.total_price }}</span>
              <span class="real-price" v-if="order.total_price !== order.real_price">
                实付：¥{{ order.real_price }}
              </span>
            </div>
            <div class="order-actions">
              <button
                  v-if="order.order_status === 0"
                  class="pay-btn"
                  @click="goToPay(order)"
              >
                去支付
              </button>
              <div class="pay-info" v-else-if="order.order_status === 1">
                <span>支付方式：{{ order.pay_method_text }}</span>
                <span>支付时间：{{ order.pay_time }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 个人资料 -->
      <div v-if="currentTab === 'profile'" class="profile-form">
        <!-- 个人资料表单 -->
      </div>

      <!-- 账号安全 -->
      <div v-if="currentTab === 'security'" class="security-settings">
        <!-- 安全设置选项 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Header from '../components/Header.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const username = ref('moluooo')
const userAvatar = ref('https://www.usian.cn/uploads/20250327/052111edb1cc05f9fd4ecebfe45264ec.png')

// 标签页配置
const tabs = [
  { id: 'orders', name: '我的订单' },
  { id: 'profile', name: '个人资料' },
  { id: 'security', name: '账号安全' }
]
const currentTab = ref('orders')

// 订单列表数据
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)




const formatDate =(dateString)=>{
  if(!dateString) return "暂无"
  const date = new Date(dateString)
  return date.getFullYear()+"-"+(String(date.getMonth()+1).padStart(2, '0'))+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()
}

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:8000/orders/list/', {
      params: {
        page: currentPage.value,
        page_size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.code === 1) {
      orders.value = response.data.data.results
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 去学习
const startStudy = (order, course) => {
  router.push({
    path: '/course-study',
    query: {
      courseId: course.id,
      orderNumber: order.order_number
    }
  })
}

// 去支付
const goToPay = (order) => {
  router.push({
    path: '/checkout',
    query: { order_number: order.order_number }
  })
}

// 功能方法
const viewOrderDetail = (order) => {
  // 查看订单详情
  ElMessage.info('订单详情功能开发中')
}

const cancelOrder = (order) => {
  // 取消订单
  ElMessage.info('取消订单功能开发中')
}

// 分页相关方法
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1 // 切换页码时重置为第一页
  getOrderList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  getOrderList()
}

onMounted(() => {
  // 获取用户信息和订单列表
  getOrderList()
})
</script>

<style scoped>
.user-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.user-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.user-profile {
  background: #2196f3;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.profile-banner {
  padding: 30px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  color: white;
}

.username {
  font-size: 24px;
  margin: 0 0 8px 0;
}

.user-title {
  margin: 0;
  opacity: 0.8;
}

.nav-tabs {
  background: white;
  border-radius: 8px;
  display: flex;
  margin-bottom: 20px;
  padding: 0 20px;
}

.tab-item {
  padding: 15px 30px;
  cursor: pointer;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #2196f3;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #2196f3;
}

.orders-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.order-item {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
}

.order-item:last-child {
  border-bottom: none;
}

.order-header {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 14px;
  margin-bottom: 15px;
}

.order-content {
  display: flex;
  gap: 20px;
}

.course-cover {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.course-info {
  flex: 1;
}

.course-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.course-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 10px 0;
}

.validity {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 14px;
}

.price {
  color: #ff6b6b;
}

.order-status {
  text-align: right;
  min-width: 120px;
}

.status-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  margin-bottom: 10px;
}

.status-tag.success {
  background: #e8f5e9;
  color: #4caf50;
}

.status-tag.pending {
  background: #fff3e0;
  color: #ff9800;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.study-btn, .detail-btn, .cancel-btn {
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
}

.study-btn {
  background: #2196f3;
  color: white;
}

.detail-btn {
  background: white;
  border: 1px solid #ddd;
  color: #666;
}

.cancel-btn {
  background: white;
  border: 1px solid #ddd;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.teacher-info {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.teacher-title {
  margin-left: 10px;
  color: #999;
}

.order-footer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.order-total {
  color: #666;
}

.total-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
  margin: 0 10px;
}

.real-price {
  color: #f56c6c;
}

.pay-info {
  color: #999;
  font-size: 12px;
}

.pay-info span {
  margin-left: 15px;
}

.pay-btn {
  padding: 8px 24px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.order-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

@media (max-width: 768px) {
  .user-container {
    padding: 10px;
  }

  .nav-tabs {
    padding: 0 10px;
  }

  .tab-item {
    padding: 15px 20px;
  }

  .order-content {
    flex-direction: column;
  }

  .course-cover {
    width: 100%;
    height: 180px;
  }

  .order-status {
    text-align: left;
  }

  .action-buttons {
    flex-direction: row;
  }
}
</style>